package com.vaha.presentation.rest;

import com.cyber.application.controller.AuthingTokenController;
import com.cyber.domain.constant.HttpResultCode;
import com.cyber.domain.entity.DataResponse;
import com.cyber.domain.entity.IdRequest;
import com.cyber.domain.entity.PagingData;
import com.cyber.domain.entity.Response;
import com.vaha.application.service.AgentService;
import com.vaha.domain.entity.Agent;
import com.vaha.domain.request.AgentRequest;
import com.vaha.domain.request.CreateAgentRequest;
import com.vaha.domain.request.UpdateAgentRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

@RestController
@RequiredArgsConstructor
public class AgentRest extends AuthingTokenController{

	private final AgentService agentService;

	@GetMapping("/agent/search")
	public Response searchAgent(@Valid AgentRequest request) {
		DataResponse<PagingData<Agent>> response = new DataResponse<>();
        Agent  agent = request.toEvent(getTenantCode());
		PagingData<Agent> agentPage = agentService.selectPage(agent);
		response.setData(agentPage);
		return response;
	}


	@GetMapping("/agent")
	public Response selectOneAgent(@Valid IdRequest idRequest) {
		DataResponse<Agent> response = new DataResponse<>();

		Agent agent = new Agent();
		agent.setId(idRequest.getId());
        agent.setTenantCode(getTenantCode());
		agent = agentService.selectOne(agent);

		response.setData(agent);
		return response;
	}

	@PostMapping("/agent")
	public Response saveAgent(@RequestBody @Valid CreateAgentRequest request) {
	    Agent  agent = request.toEvent(getSessionId(),getTenantCode());

		int result = agentService.save(agent);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@PutMapping("/agent")
	public Response updateAgent(@RequestBody @Valid UpdateAgentRequest request) {
	    Agent  agent = request.toEvent(getSessionId(),getTenantCode());
		int result = agentService.updateById(agent);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@DeleteMapping("/agent")
	public Response deleteAgent(@Valid IdRequest idRequest) {
		Agent agent = new Agent();
		agent.setId(idRequest.getId());

		agent.setTenantCode(getTenantCode());
		agent.setUpdator(getSessionId());
        agent.setUpdateTime(new Date());

		int result = agentService.deleteById(agent);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}
}
